import { createStore, applyMiddleware, combineReducers } from "redux";
import asyncMiddleware from "./asyncMiddleware";
import handleReducer from "./handleReducer";

export default (models, middleware) => {
  let resultReducers = {};

  for (let key in models) {
    const model = models[key];
    const { namespace, reducers, flows, state } = model;
    if (resultReducers[namespace]) {
      throw new Error(`${namespace} is repeated in reducers`);
    }

    const currentReducers = handleReducer(model);
    resultReducers = Object.assign({}, resultReducers, {
      [namespace]: currentReducers
    });
  }

  const reducer = combineReducers(resultReducers);
  return createStore(
    reducer,
    applyMiddleware(...middleware, asyncMiddleware())
  );
};
